﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CarShop.UserInterface.Wpf.Core.Commands;
using CarShop.UserInterface.Wpf.Core.EventArgs;

namespace CarShop.UserInterface.Wpf.Core.ViewModels
{
    public abstract class ApplicableDialogWindowViewModel : ViewModelBase
    {
        #region Events

        public event EventHandler<RequestApplyEventArgs> RequestApply;

        #endregion


        #region Fields

        private ICommand _applyCommand;
        private ICommand _applyAndCloseCommand;

        #endregion


        #region Properties

        public ICommand ApplyCommand
        {
            get
            {
                return _applyCommand ??
                    (_applyCommand = new SimpleCommand(this.OnApply, this.CanApply));
            }
        }

        public ICommand ApplyAndCloseCommand
        {
            get
            {
                return _applyAndCloseCommand ??
                    (_applyAndCloseCommand = new SimpleCommand(this.OnApplyAndClose, this.CanApplyAndClose));
            }
        }

        #endregion


        #region Command Handlers

        protected virtual void OnApply()
        {
            this.OnRequestApply(true);
        }

        protected virtual bool CanApply()
        {
            return true;
        }

        protected virtual void OnApplyAndClose()
        {
            this.OnRequestApply(false);
        }

        protected virtual bool CanApplyAndClose()
        {
            return true;
        }

        #endregion


        protected virtual void OnRequestApply(bool withoutClosing)
        {
            var handler = Interlocked.CompareExchange(ref RequestApply, null, null);

            if (handler != null)
            {
                handler(this, new RequestApplyEventArgs(withoutClosing));
            }
        }
    }
}
